package tingshu.servlet.track;

import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import tingshu.service.TrackService;
import tingshu.util.Log;
import tingshu.view_object.StudioTrackListView;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author houdaiqin
 * @date 2022/07/14 09:53
 **/
@WebServlet("/studio/track/list.json")
public class ListJsonServlet extends HttpServlet {
    private final TrackService trackService=new TrackService();
    private final ObjectMapper objectMapper=new ObjectMapper();
    public ListJsonServlet() {
        // 这一步可以不写，目的是让序列化出来的 JSON 带有空格和换行
        objectMapper.setDefaultPrettyPrinter(new DefaultPrettyPrinter());
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Log.println("访问 GET /studio/track/list.json");
        
        int page;
        String pageString = req.getParameter("page");
        if (pageString==null||pageString.trim().isEmpty()){
            Log.println("请求参数中没有携带页码信息，默认为第一页");
            page=1;
        }else{
            pageString=pageString.trim();
            try {
                page = Integer.parseInt(pageString);
            }catch (NumberFormatException e){
                Log.println("请求参数中的 页码 信息不是数字，默认成第 1 页");
                page = 1;
            }
        }

        StudioTrackListView resultView=new StudioTrackListView();
        //1.获取当前登录用户
        HttpSession session= req.getSession(false);
        UserVO currentUser=null;
        if (session!=null){
            currentUser=(UserVO) session.getAttribute("currentUser");
        }
        //2.用户未登录
        if (currentUser==null){
            Log.println("用户未登录");
            resultView=null;
        }else{
            Log.println("用户已登录");
            //得到当前用户的所有音频列表
            resultView=trackService.listOfUser(currentUser,page);
        }
        Log.println("准备JSON序列化的结果是"+resultView);
        // 使用 Jackson 提供代码，将 list 对象，转化成（序列化）字符串类型的、JSON 格式
        String json = objectMapper.writeValueAsString(resultView);
        Log.println("JSON 序列化后的结果是: " + json);

        // 响应该字符串
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        Log.println("将 JSON 写入响应体中");
        writer.println(json);
    }
}